const https = require("https");
const { createProxyMiddleware } = require('http-proxy-middleware')
const { parse } = require("url");
const next = require("next");
const fs = require("fs");
const path = require("path");

const port = process.env.PORT || 443;
const dev = process.env.NODE_ENV !== "production";
const target = "http://127.0.0.1:18091/chat"

const app = next({
  dev,
  dir: path.join(__dirname),
  conf: {
    distDir: "build",
  },
});
const handle = app.getRequestHandler();

const httpsOptions = {
  key: fs.readFileSync(path.resolve(__dirname, "./cert/chat.cebserv.com.key")),
  cert: fs.readFileSync(path.resolve(__dirname, "./cert/chat.cebserv.com.pem")),
};

const apiProxy = createProxyMiddleware('/api', {
  target,
  changeOrigin: true, // 要求接口服务器支持跨域
  pathRewrite: { '^/api': '' }, // 去掉/api路径前缀
  onProxyRes: function (proxyRes) {
    proxyRes.headers['Access-Control-Allow-Origin'] = '*';
  }
});

app.prepare().then(() => {
  https.createServer(httpsOptions, (req, res) => {
    const parsedUrl = parse(req.url, true)
    const { pathname, query } = parsedUrl

    if (pathname.startsWith('/api')) {

      apiProxy(req, res)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on https://localhost:${port}`)
  })
})